#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import os.path
import shutil
import sys
import time

from ferrisWheelAnalysis import ferris_wheel_analysis
from texasHoldemPokerAnalysis import texas_holdem_poker_analysis
from qiniu import Auth, put_file, etag
from pathlib import Path
from tools import get_specified_timestamps
import requests
import json
import hashlib
import base64
import hmac
import qiniu
from qiniu import CdnManager
from os.path import basename


def upload_qiniu():
    access_key = '7JZeFZUuPgjgOX2taqQz3b09LzehXKIEPxXXvs2I'
    secret_key = '2v7115eYeAzqyPuCH4yXjk2qd_9dEUdso91ejn0R'

    q = Auth(access_key, secret_key)

    bucket_name = 'azal'

    start_time, end_time = get_specified_timestamps()
    parent_dir_path = Path(datetime.datetime.fromtimestamp(start_time).strftime("%Y-%m-%d"))

    upload_result = []
    for file_path in parent_dir_path.rglob('*'):
        if file_path.is_file():

            # 构建上传后保存的文件名
            relative_path = file_path.relative_to(parent_dir_path)
            # 拼接七牛云存储路径
            key = Path("temp") / "game" / parent_dir_path / relative_path
            # 将路径转换为字符串并确保使用正斜杠
            key_str = str(key).replace(os.sep, '/')
            # print(f"---->{key_str}   {file_path}")

            # 生成上传 Token，可以指定过期时间等
            token = q.upload_token(bucket_name, key_str, 3600)
            # 要上传文件的本地路径
            ret, info = put_file(token, key_str, file_path, version='v2')
            if info.status_code == 200:
                text_body_json = json.loads(info.text_body)
                url = f"https://qn.azallivegroup.com/{text_body_json.get('key')}"
                upload_result.append(url)

    return upload_result


def flush_cdn_file(urls):
    # 账户ak，sk
    access_key = '7JZeFZUuPgjgOX2taqQz3b09LzehXKIEPxXXvs2I'
    secret_key = '2v7115eYeAzqyPuCH4yXjk2qd_9dEUdso91ejn0R'

    auth = qiniu.Auth(access_key=access_key, secret_key=secret_key)
    cdn_manager = CdnManager(auth)

    # 刷新链接
    refresh_url_result = cdn_manager.refresh_urls(urls)
    print(refresh_url_result)


def send_feishu_message(result):
    url = "https://open.feishu.cn/open-apis/bot/v2/hook/0384c305-8a4f-4bbd-8b2d-cfa51b4dfa46"

    content_array = []
    for file_url in result:
        key = basename(file_url)
        result_dict = {"tag": "a", "text": f"{key}\n\n", "href": file_url}
        content_array.append(result_dict)

    print(content_array)

    content = {
        "post": {
            "zh-CN":{
                "title":"概率游戏每日信息统计",
                "content": [content_array]
            }
        }

    }

    secret = "azOeh05VFII2n5Xz6PL0Oh"
    timestamp = int(time.time())
    sign = gen_sign(timestamp, secret)

    headers = {
        "Content-Type": "application/json"
    }

    data_payload = {
        'msg_type': 'post',
        'content': content,
        'timestamp': timestamp,
        "sign": sign
    }
    print(json.dumps(data_payload, indent=4, ensure_ascii=False))
    try:
        response = requests.post(url, headers=headers, data=json.dumps(data_payload, ensure_ascii=False))
        response.raise_for_status()
        print(response.text)

        return response.json()
    except requests.RequestException as e:
        print(f"请求发生错误: {e}")
    except ValueError:
        print("无法解析响应为 JSON 格式")
    return None

def gen_sign(timestamp, secret):
    # 拼接timestamp和secret
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
    # 对结果进行base64处理
    sign = base64.b64encode(hmac_code).decode('utf-8')
    return sign


if __name__ == "__main__":
    try:
        ferris_wheel_analysis()
        texas_holdem_poker_analysis()
        upload_result = upload_qiniu()
        if not upload_result or len(upload_result) != 4:
            sys.exit(1)
        flush_cdn_file(upload_result)
        result = send_feishu_message(upload_result)
        if result is not None:
            try:
                start_time, end_time = get_specified_timestamps()
                parent_dir_path = Path(datetime.datetime.fromtimestamp(start_time).strftime("%Y-%m-%d"))
                shutil.rmtree(parent_dir_path)
                print(f"目录 {parent_dir_path} 及其内容删除成功")
            except OSError as e:
                print(f"删除目录时发生错误: {e}")
    except Exception as e:
        print(e)
        sys.exit(1)